package com.example.e_comm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.e_comm.entity.Permission;
import com.example.e_comm.entity.Role;
import com.example.e_comm.entity.RolePermission;
import com.example.e_comm.mapper.PermissionMapper;
import com.example.e_comm.mapper.RoleMapper;
import com.example.e_comm.mapper.RolePermissionMapper;
import com.example.e_comm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class RoleServiceImpl
        extends ServiceImpl<RoleMapper, Role>
        implements RoleService {
    @Autowired
    private RoleMapper mapper;
    @Autowired
    private PermissionMapper permissionService;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;


    @Override
    public void assignRole(Long roleId, List<Long> pIds) {
        //清空角色原有权限关系-role_permission数据表
        rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id",roleId));
        //为角色分配新的权限
        if (pIds != null && pIds.isEmpty()){
            List<RolePermission> rps=pIds.stream()
                    .map(pId ->{
                        RolePermission rp=new RolePermission();
                        rp.setRoleId(roleId);
                        rp.setPermissionId(pId);
                        return rp;
                    }).collect(Collectors.toList());
            //批量插入角色权限关系
            for(RolePermission rp:rps){
                rolePermissionMapper.insert(rp);
            }
        }
    }

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return mapper.getRolesByUserId(userId);
    }
    @Override
    public Role getRoleByIdWithPermissions(Long roleId) {
        //获取角色详情
        Role role=this.getById(roleId);
        //查询角色的权限列表
        if (role != null){
            List<Permission> permissions=permissionService.getPermissionsByRoleId(roleId);
            role.setPermissions(permissions);
        }
        return role;
    }
    @Override
    public IPage<Role> search(IPage<Role> page, String keyword) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()){  // 修正 StringUtil.isNullOrEmpty 的逻辑
            wrapper.like("name", keyword)  // 使用正确的字段名
                    .or()
                    .like("description", keyword);  // 使用正确的字段名
        }
        return mapper.selectPage(page, wrapper);
    }
//69-77改

}